<template>
	<view class="page-container">
		<!-- 导航栏（含回退按钮） -->
		<view class="nav-bar">
			<view class="back-btn" @click="navigateBack">
				<uni-icons type="back" size="32" color="#333"></uni-icons>
			</view>
			<view class="page-title">我的收货地址</view>
		</view>

		<!-- 地址列表（卡片式，点击地址项切换定位） -->
		<view class="address-list">
			<view v-for="(item, index) in addressList" :key="item.id || index"
				class="card address-card mb-md hover-scale" @click="selectAddress(item)">
				<view class="address-content">
					<view class="address-info flex justify-between">
						<text class="name">{{item.contactName}}</text>
						<text class="phone">{{item.contactPhone}}</text>
					</view>
					<view class="address-detail">
						<text>{{item.address}}</text>
					</view>
				</view>
				<view class="address-actions flex justify-end">
					<view class="action-btn btn btn--text hover-press" @click.stop="editAddress(item)">编辑</view>
					<view class="action-btn btn btn--text action-btn--danger hover-press"
						@click.stop="deleteAddress(item.id)">删除</view>
				</view>
			</view>
		</view>

		<!-- 添加地址按钮 -->
		<view class="add-btn">
			<button class="btn btn--primary btn--block" @click="addAddress">添加新地址</button>
		</view>
	</view>
</template>
<script>
	import {
		get,
		del
	} from '@/utils/request'
	import {
		mapGetters
	} from 'vuex'
	import uniIcons from '@/components/uni-icons/uni-icons.vue'

	export default {
		components: {
			uniIcons
		},
		computed: {
			...mapGetters({
				userId: 'user/userId'
			})
		},
		data() {
			return {
				addressList: []
			}
		},
		onShow() {
			this.loadAddressList()
		},
		methods: { // 这里只保留一个methods对象
			navigateBack() {
				uni.navigateBack({
					delta: 1
				});
			},

			async selectAddress(item) {
				try {
					uni.showLoading({
						title: '处理中...'
					});

					// 1. 获取经纬度
					const geoRes = await this.$api.addressApi.geocode(item.address);
					if (geoRes.code !== 200) throw new Error('地址解析失败');

					// 2. 更新Vuex（包含完整地址信息）
					await this.$store.dispatch('address/updateSelectedAddress', {
						contactName: item.contactName,
						contactPhone: item.contactPhone,
						address: item.address,
						longitude: geoRes.data.longitude,
						latitude: geoRes.data.latitude
					});
					console.log('Vuex存储的地址数据：', item);
					uni.setStorageSync('selectedAddress', item);


					// 4. 返回原页面
					uni.hideLoading();
					uni.navigateBack();

				} catch (e) {
					uni.hideLoading();
					uni.showToast({
						title: '地址选择失败',
						icon: 'none'
					});
				}
			},

			async loadAddressList() {
				if (!this.userId) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}, 1000)
					return
				}

				try {
					const res = await get('/user/address/list', {
						customerId: this.userId
					})
					if (res.code === 200) {
						console.log('地址数据：', res.data)
						this.addressList = res.data || [];
						console.log('地址数据：', this.addressList);
					}
				} catch (e) {
					uni.showToast({
						title: '获取地址列表失败',
						icon: 'none'
					})
				}
			},

			addAddress() {
				uni.navigateTo({
					url: '/pages/user/address/edit',
					animationType: 'slide-in-right',
					animationDuration: 300
				})
			},

			editAddress(item) {
				uni.navigateTo({
					url: `/pages/user/address/edit?id=${item.id}`,
					animationType: 'slide-in-right',
					animationDuration: 300
				})
			},

			async deleteAddress(id) {
				try {
					const confirm = await new Promise(resolve => {
						uni.showModal({
							title: '提示',
							content: '确定要删除该地址吗？',
							success: (res) => resolve(res.confirm)
						})
					})
					if (!confirm) return;

					uni.showLoading({
						title: '删除中'
					})
					const res = await del(`/user/address/${id}`)
					if (res.code === 200) {
						uni.showToast({
							title: '删除成功'
						})
						this.loadAddressList()
					} else {
						uni.showToast({
							title: res.msg || '删除失败',
							icon: 'none'
						})
					}
				} catch (e) {
					uni.showToast({
						title: '删除失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			}
		}
	}
</script>


<style lang="scss">
	// 导航栏样式
	.nav-bar {
		display: flex;
		align-items: center;
		height: 88rpx; // 适配小程序导航栏高度
		padding: 0 20rpx;
		border-bottom: 1px solid var(--color-border-light);
		background-color: #fff;

		.back-btn {
			width: 60rpx;
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;

			// 点击反馈
			&:active {
				background-color: rgba(0, 0, 0, 0.05);
				border-radius: 50%;
			}
		}

		.page-title {
			flex: 1;
			text-align: center;
			font-size: 32rpx;
			font-weight: 500;
			color: #333;
		}
	}

	.address-list {
		margin: 20rpx 0 140rpx; // 顶部留出导航栏空间
		padding: 0 20rpx;
	}

	.address-card {
		padding: var(--spacing-md);
		background-color: #fff;
		border-radius: 10rpx;
		margin-bottom: var(--spacing-md);
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		transition: transform 0.2s;

		// 点击缩放效果
		&.hover-scale:active {
			transform: scale(0.99);
		}

		.address-content {
			margin-bottom: var(--spacing-md);
			padding-bottom: var(--spacing-md);
			border-bottom: 1px solid var(--color-border-light);
		}

		.address-info {
			margin-bottom: var(--spacing-sm);

			.name {
				font-size: var(--font-lg);
				font-weight: 500;
				color: var(--color-text);
			}

			.phone {
				font-size: var(--font-base);
				color: var(--color-text-light);
			}
		}

		.address-detail {
			font-size: var(--font-base);
			color: var(--color-text);
			line-height: 1.5;
		}

		.address-actions {
			.action-btn {
				margin-left: var(--spacing-md);
				font-size: var(--font-base);
				padding: 5rpx 0;
			}

			.action-btn--danger {
				color: var(--color-danger);
			}

			// 按钮点击反馈
			.hover-press:active {
				background-color: rgba(0, 0, 0, 0.05);
				border-radius: 4rpx;
			}
		}
	}

	.add-btn {
		position: fixed;
		bottom: 40rpx;
		left: 0;
		right: 0;
		padding: 0 var(--spacing-md);
	}
</style>